//
//  SSUserOrderDoneView.swift
//  拾舍清洁
//
//  Created by sky.wei on 2023/3/13.
//

import UIKit

import AVFoundation
import Photos
import Photos
import Alamofire
import SwiftyJSON

public typealias SSResultClosure = ()->()

class SSUserOrderDoneView: UIView ,UIImagePickerControllerDelegate,UIActionSheetDelegate,UINavigationControllerDelegate{
    
    var resultClosure: SSResultClosure?     // 闭包
    
    @IBOutlet weak var whiteView: UIView!
    @IBOutlet weak var QRCodeImgV: UIImageView!
    @IBOutlet weak var saveBtn: UIButton!
    @IBOutlet weak var bgView: UIView!
    
    var getCouponResult: GetCouponResult?     // 闭包
    
    class func orderDoneView()->SSUserOrderDoneView{
        let view = Bundle.main.loadNibNamed("SSUserOrderDoneView", owner: nil, options: nil)?.last as! SSUserOrderDoneView
        view.frame = CGRect(x: 0, y: 0, width: ScreenWidth, height: ScreenHeight)
        dissmissToEscaping {
            keyWindow?.addSubview(view)
        }
        return view
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        
        
        
        saveBtn.layer.masksToBounds = true
        saveBtn.layer.cornerRadius = 22
        
        whiteView.layer.masksToBounds = true
        whiteView.layer.cornerRadius = 8
        
        
        bgView.backgroundColor = UIColor.black.withAlphaComponent(0.5)
        
        getQRCodeNetwork()
    }
    
    //qrcode
    func getQRCodeNetwork() {
        HttpConnectTools.share.request(urlString: APIUrl.share.getVxImg_URL, parameters: nil) { (result, error) in
            if let _ = result{
                let json = JSON(parseJSON: result!)
                let retCode = json["retCode"].stringValue
                let retMsg = json["retMsg"].stringValue
                if(retCode == "0000"){
                    let url = json["data"]["vxImgUrl"].string
                    self.QRCodeImgV.setImage(with: url, placeholderImage: UIImage(named: "")) { image, error in
                    }
                }else{
                    dissmissToTast(msg: "\(retMsg)")
                }
            }
        }
    }

    @IBAction func cancelAction(_ sender: Any) {
        removeFromSuperview()
        resultClosure?()
    }
    
    @IBAction func saveAction(_ sender: Any) {
        accessCameraAuthority { b in
            
        }
    }
    
    /// 获取权限
    ///
    /// - Parameter accessBlock:  闭包回调
    func accessCameraAuthority(accessBlock: ((Bool) -> Void)? = nil)
    {
        
        let library:PHAuthorizationStatus = PHPhotoLibrary.authorizationStatus()
        if(library == PHAuthorizationStatus.authorized){
//            makeToast("authorized")
            let image = UIImage()
            UIImageWriteToSavedPhotosAlbum(QRCodeImgV.image ?? image, self, #selector(save(image:didFinishSavingWithError:contextInfo:)), nil)
        } else if(library == PHAuthorizationStatus.notDetermined){
//            makeToast("notDetermined")
            let image = UIImage()
            UIImageWriteToSavedPhotosAlbum(QRCodeImgV.image ?? image, nil, nil, nil)
        }else{
            makeToast("未授权")
        }

    }
    
    @objc func save(image:UIImage, didFinishSavingWithError:NSError?,contextInfo:AnyObject) {
          
          if didFinishSavingWithError != nil {
              makeToast("保存失败")
          } else {
              removeFromSuperview()
              makeToast("保存成功")
              resultClosure?()
          }
      }
    
    func resultClosure(_ finished: @escaping SSResultClosure) {
        resultClosure = finished
    }
}
